// Package repository internal/repository/login_info_repository.go
package repository

import (
	"gorm.io/gorm"
	"gozrd-admin-api/internal/entity/model"
)

// ILoginInfoRepository 登录日志仓储接口
type ILoginInfoRepository interface {
	CreateLoginInfo(info model.SysLoginInfo) error
	GetLoginInfoList(pageNum, pageSize int, username, loginStatus, beginTime, endTime string) ([]model.SysLoginInfo, int64, error)
	BatchDeleteLoginInfo(ids []int) error
	DeleteLoginInfoById(id int) error
	CleanLoginInfo() error
}

// LoginInfoRepository 登录日志仓储实现
type LoginInfoRepository struct {
	db *gorm.DB
}

// NewLoginInfoRepository 创建登录日志仓储
func NewLoginInfoRepository(db *gorm.DB) ILoginInfoRepository {
	return &LoginInfoRepository{
		db: db,
	}
}

// CreateLoginInfo 新增登录日志
func (r *LoginInfoRepository) CreateLoginInfo(info model.SysLoginInfo) error {
	return r.db.Create(&info).Error
}

// GetLoginInfoList 分页查询登录日志
func (r *LoginInfoRepository) GetLoginInfoList(pageNum, pageSize int, username, loginStatus, beginTime, endTime string) ([]model.SysLoginInfo, int64, error) {
	var logs []model.SysLoginInfo
	var count int64

	db := r.db.Model(&model.SysLoginInfo{})

	// 添加查询条件
	if username != "" {
		db = db.Where("username = ?", username)
	}
	if loginStatus != "" {
		db = db.Where("login_status = ?", loginStatus)
	}
	if beginTime != "" && endTime != "" {
		db = db.Where("login_time BETWEEN ? AND ?", beginTime, endTime)
	}

	// 获取总数
	err := db.Count(&count).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).
		Order("login_time desc").
		Find(&logs).Error

	return logs, count, err
}

// BatchDeleteLoginInfo 批量删除登录日志
func (r *LoginInfoRepository) BatchDeleteLoginInfo(ids []int) error {
	return r.db.Where("id in (?)", ids).Delete(&model.SysLoginInfo{}).Error
}

// DeleteLoginInfoById 删除单条登录日志
func (r *LoginInfoRepository) DeleteLoginInfoById(id int) error {
	return r.db.Delete(&model.SysLoginInfo{}, id).Error
}

// CleanLoginInfo 清空登录日志
func (r *LoginInfoRepository) CleanLoginInfo() error {
	return r.db.Exec("TRUNCATE TABLE sys_login_info").Error
}
